﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using SplashOn_PhoneLib;
using System.Windows.Navigation;
using Microsoft.Xna.Framework.Input.Touch;

namespace SplashOn_Phone
{
    public partial class Wayfinding : PhoneApplicationPage
    {
        public event PropertyChangedEventHandler PropertyChanged;
        ContentManager contentManager;
        GameTimer timer;
        // For rendering the XAML onto a texture
        UIElementRenderer elementRenderer;

        SplashOn_Phone_Main splashOn_Phone_Main;

        public Brush SelectedArgbBrush
        {
            get;
            set;
        }

        public Wayfinding()
        {
            InitializeComponent();
            this.DataContext = this;

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            splashOn_Phone_Main = new SplashOn_Phone_Main();

            LayoutUpdated += new EventHandler(GamePage_LayoutUpdated);
        }        

        void GamePage_LayoutUpdated(object sender, EventArgs e)
        {
            // Create the UIElementRenderer to draw the XAML page to a texture.

            // Check for 0 because when we navigate away the LayoutUpdate event
            // is raised but ActualWidth and ActualHeight will be 0 in that case.
            if (ActualWidth > 0 && ActualHeight > 0 && elementRenderer == null)
            {
                elementRenderer = new UIElementRenderer(this, (int)640, (int)480);
            }
        }        

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            StartTransitionFromGamePage();
            
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            TouchPanel.EnabledGestures = GestureType.Flick | GestureType.Tap;

            splashOn_Phone_Main.Initialize(SharedGraphicsDeviceManager.Current, contentManager, viewfinderBrush, true);

            timer.Start();

            base.OnNavigatedTo(e);       

            try
            {
                NavigationService.RemoveBackEntry();
            }
            catch (InvalidOperationException exe)
            {
                DebugHelper.w(exe.Message);
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            splashOn_Phone_Main.Dispose();

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            HandleTouchInput();
            splashOn_Phone_Main.Update(e.ElapsedTime, this.IsEnabled, true);
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            //SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);
            elementRenderer.Render();

            if (splashOn_Phone_Main.VideoBackground == null)
                splashOn_Phone_Main.VideoBackground = elementRenderer.Texture;

            splashOn_Phone_Main.Draw(e.ElapsedTime);
        }

        private void HandleTouchInput()
        {
            TouchCollection touches = TouchPanel.GetState();

            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                
                switch (gesture.GestureType)
                {
                    case GestureType.Flick:
                        System.Diagnostics.Debug.WriteLine(":: gesture.Delta.X=" + gesture.Delta.X);
                        System.Diagnostics.Debug.WriteLine(":: gesture.Delta.Y=" + gesture.Delta.Y);
                        if (gesture.Delta.Y < -1000)   // to go DOWN
                        {
                            NavigationService.Navigate(new Uri(string.Format("/Wayfinding.xaml"), UriKind.Relative));
                        }
                       
                        break;

                    case GestureType.Tap:
                        System.Diagnostics.Debug.WriteLine(":: tap gesture.Delta=" + gesture.Delta.ToString());
                        System.Diagnostics.Debug.WriteLine(":: tap gesture.Position=" + gesture.Position.ToString());

                        String paramsa = "wayFindingX=" + gesture.Position.X.ToString() +
                                    "&wayFindingY=" + gesture.Position.Y.ToString();
                                    
                        DebugHelper.w(" --> " + paramsa);
                        NavigationService.Navigate(new Uri("/GamePage.xaml?" + paramsa, UriKind.Relative));
                        StartTransitionToGamePage();
                        break;
                }
            }
        }
        private void StartTransitionToGamePage()
        {
            SlideTransition slideTransition = new SlideTransition();
            slideTransition.Mode = SlideTransitionMode.SlideUpFadeOut;

            PhoneApplicationPage phoneApplicationPage =
            (PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;

            ITransition transition = slideTransition.GetTransition(phoneApplicationPage);
            transition.Completed += delegate
            {
                transition.Stop();
            };
            transition.Begin();
        }

        private void StartTransitionFromGamePage()
        {
            SlideTransition slideTransition = new SlideTransition();
            slideTransition.Mode = SlideTransitionMode.SlideDownFadeIn;

            PhoneApplicationPage phoneApplicationPage =
            (PhoneApplicationPage)(((PhoneApplicationFrame)Application.Current.RootVisual)).Content;

            ITransition transition = slideTransition.GetTransition(phoneApplicationPage);
            transition.Completed += delegate
            {
                transition.Stop();
            };
            transition.Begin();
        }
        
    }
}